package net.hn.hnms.biz.indicator.service;

import cn.hutool.core.lang.Assert;
import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.indicator.dao.DwsMineMathematicalModelMapper;
import net.hn.hnms.biz.indicator.dao.DwsMineModelParametersMapper;
import net.hn.hnms.biz.indicator.entity.ChartAnaliseVo;
import net.hn.hnms.biz.indicator.entity.DwsMineMathematicalModel;
import net.hn.hnms.biz.indicator.entity.DwsMineModelParameters;
import net.hn.hnms.biz.indicator.entity.MineMathematicalModelDTO;
import net.hn.hnms.biz.indicator.util.OweDateUtils;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.utils.DateUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 智呈物联 nzw
 * @date 2022/9/20
 */
@Service
@RequiredArgsConstructor
public class DwsMineMathematicalModelService {
    private final JdbcTemplate locationJdbcTemplate;
    DwsMineMathematicalModelMapper dwsMineMathematicalModelMapper;
    DwsMineModelParametersMapper dwsMineModelParametersMapper;

    @Autowired
    public void setDwsMineModelParametersMapper(DwsMineModelParametersMapper dwsMineModelParametersMapper) {
        this.dwsMineModelParametersMapper = dwsMineModelParametersMapper;
    }

    @Autowired
    public void setDwsMineMathematicalModelMapper(DwsMineMathematicalModelMapper dwsMineMathematicalModelMapper) {
        this.dwsMineMathematicalModelMapper = dwsMineMathematicalModelMapper;
    }

    public ResponsePage<Map<String,Object>> pageList(PageQuery pageQuery, String modelName, String modelType){
        StringBuffer sql = new StringBuffer("select * from dws_mine_mathematical_model where 1=1 ");
        if (modelName!=null&&!"".equals(modelName)){
            sql.append("and model_name like '%"+modelName+"%'");
        }
        if (modelType!=null&&!"".equals(modelType)){
            sql.append(" and model_type = '"+modelType+"'");
        }
        Integer pageSize = pageQuery.getPageSize();
        Integer pageNum = pageQuery.getPageNum();
        int totalElements = locationJdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DwsMineMathematicalModel.class)).size();
        if (pageSize==null){
            pageSize = 10;
        }
        if(pageNum==null||pageNum==0){
            pageNum = 1;
        }
        pageNum = (pageNum-1)*pageSize;
        sql.append("LIMIT '"+pageSize+"' OFFSET '"+pageNum+"'");
        List<DwsMineMathematicalModel> list = locationJdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DwsMineMathematicalModel.class));

        return new ResponsePage<>(list,totalElements);
    }

    public Map<String,Object> listByModel(Long modelId){
        Assert.notNull(modelId,"模型id不能空");
        StringBuffer sql = new StringBuffer("SELECT\n" +
                "\t* \n" +
                "FROM\n" +
                "\tdws_mine_model_parameters \n" +
                "WHERE\n" +
                "\tmodel_id = '\n" +
                modelId+
                "'ORDER BY\n" +
                "\tcreate_time");
        List<DwsMineModelParameters> list = locationJdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DwsMineModelParameters.class));
        Map<String,Object> map = new HashMap<>();
        map.put("content",list);
        map.put("totalElements",list.size());
        return map;
    }

    public void update(MineMathematicalModelDTO mineMathematicalModelDTO){
        Assert.notNull(mineMathematicalModelDTO.getId(),"id不能为空");
        List<DwsMineModelParameters> parameters = mineMathematicalModelDTO.getParameters();
        parameters.forEach(item->{
            Assert.notBlank(item.getModelParamName(),"模型名称不能为空");
            item.setModelId(mineMathematicalModelDTO.getId());
        });
        for (DwsMineModelParameters dwsMineModelParameters:parameters){
            dwsMineModelParametersMapper.save(dwsMineModelParameters);
        }
        String sql = "UPDATE dws_mine_mathematical_model set model_formula = '"+mineMathematicalModelDTO.getModelFormula()+"'"
                +",indicator_description='"+mineMathematicalModelDTO.getIndicatorDescription()+"' where id="+mineMathematicalModelDTO.getId();
        locationJdbcTemplate.execute(sql);
    }

    public List<ChartAnaliseVo> gasIndicatorTrend(String mineCode) {
        List<ChartAnaliseVo> result = new ArrayList<>();
        String endTime = DateUtils.getDate();
        String startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(DateUtils.getNowDate(), -30));
        List<String> day = OweDateUtils.getXData(startTime, endTime, "day");
        String sql = "SELECT t.dataTime x, sum(t.pointValue) y \n" +
                "FROM (\n" +
                "    SELECT \n" +
                "        indicator_first_level_code, \n" +
                "        indicator_second_level_code, \n" +
                "        indicator_third_level_code, \n" +
                "        time_bucket(interval '1 day', data_time) AS dataTime, \n" +
                "        last(indicator_value, data_time) AS pointValue \n" +
                "    FROM znjc.ssys_mine_indicator_model \n" +
                "    WHERE \n" +
                "        indicator_first_level_code = '30' \n" +
                "        AND (indicator_third_level_code = '' OR indicator_third_level_code IS NULL) \n" +
                "        AND mine_code = '%s'\n" +
                "        AND data_time >= '%s'\n" +
                "        AND data_time <= '%s'\n" +
                "    GROUP BY \n" +
                "        indicator_first_level_code, \n" +
                "        indicator_second_level_code, \n" +
                "        indicator_third_level_code, \n" +
                "        time_bucket(interval '1 day', data_time)\n" +
                ") t \n" +
                "GROUP BY t.dataTime;";
        sql=String.format(sql,mineCode,startTime,endTime);
        List<ChartAnaliseVo> chartData = locationJdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ChartAnaliseVo.class));
        day.forEach(x -> {
            ChartAnaliseVo chartAnaliseVo = chartData.stream().filter(item -> item.getX().contains(x)).findFirst().orElse(new ChartAnaliseVo(x, "0", ""));
            result.add(chartAnaliseVo);
        });
        return result;
    }

}
